<template>
  <div class="vaw-tab-bar-container">
    <div class="vaw-tab-bar-body">
      <span class="arco-icon-hover" :class="{ loadaing: refreshLoading }" @click="refreshRoute">
        <icon-sync />
      </span>
      <div style="flex: 1; overflow: hidden">
        <a-tabs v-model:active-key="currentTab" type="card-gutter" editable @delete="closeTab" @change="tabChange">
          <a-tab-pane
            v-for="item of getVisitedRoutes"
            :key="item.fullPath"
            :title="item.meta ? item.meta.title : item.name"
            :closable="!item.meta?.affix"
            destroy-on-hide
          />
        </a-tabs>
      </div>

      <a-dropdown>
        <div class="close-opt">关闭操作 <icon-down /></div>
        <template #content>
          <a-doption @click="closeAll">关闭全部</a-doption>
          <a-doption @click="closeOther">关闭其他</a-doption>
        </template>
      </a-dropdown>
    </div>

    <!-- <ul v-show="showContextMenu" class="contex-menu-wrapper" :style="contextMenuStyle">
      <li>
        <a-button type="text" @click="refreshRoute">
          <template #icon>
            <ReloadOutlined style="vertical-align: text-bottom" />
          </template>
          刷新页面
        </a-button>
      </li>
      <li :disabled="showLeftMenu">
        <a-button :disabled="showLeftMenu" type="text" @click="closeLeft">
          <template #icon>
            <ArrowLeftOutlined style="vertical-align: text-bottom" />
          </template>
          关闭左侧
        </a-button>
      </li>
      <li :disabled="showRightMenu">
        <a-button :disabled="showRightMenu" type="text" @click="closeRight">
          <template #icon>
            <ArrowRightOutlined style="vertical-align: text-bottom" />
          </template>
          关闭右侧
        </a-button>
      </li>
      <li>
        <a-button type="text" @click="closeAll">
          <template #icon>
            <CloseOutlined style="vertical-align: text-bottom" />
          </template>
          关闭所有
        </a-button>
      </li>
    </ul> -->
  </div>
</template>

<script lang="ts">
  /**
   * 需要搭配hooks/useNavigate使用
   * 刷新页面保留访问记录
   *
   * 页面顶部的访问记录tabs✅
   * @case 打开新标签
   * 名字动态，多次通过新增、详情（相同id）、编辑（相同id）进入同一个页面
   *
   * @case 关闭页面✅
   * 关闭当前标签页，返回前一个标签
   *
   * @case 底部按钮确认✅
   * 回到发起页面，并刷新列表数据，清空筛选条件
   *
   */
  import { mapState, mapActions } from 'pinia'
  import { defineComponent, unref } from 'vue'

  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
  export default defineComponent({
    name: 'TabBar',
    data() {
      return {
        currentTab: this.$route.fullPath,
        contextMenuStyle: {
          left: '0',
          top: '0',
        },
        showContextMenu: false,
        selectRoute: {},
        showLeftMenu: true,
        showRightMenu: true,
        refreshLoading: false,
      }
    },
    computed: {
      ...mapState(useVisitedRouteStore, ['getVisitedRoutes']),
    },
    watch: {
      $route: {
        handler(newVal) {
          this.currentTab = newVal.fullPath || ''
        },
        immediate: true,
      },
      showContextMenu(val) {
        if (val) {
          document.body.addEventListener('click', this.closeMenu)
        } else {
          document.body.removeEventListener('click', this.closeMenu)
        }
      },
    },
    methods: {
      ...mapActions(useVisitedRouteStore, [
        'removeVisitedRoute',
        'findLastRoutePath',
        'closeRightVisitedView',
        'closeLeftVisitedView',
        'closeAllVisitedView',
        'closeOtherVisitedView',
      ]),
      tabChange(path: RouteLocationNormalized) {
        this.$router.push(path)
      },
      itemChildClick(path: RouteLocationNormalized, e: MouseEvent) {
        this.handleTabClick((e.target as HTMLElement).parentElement?.parentElement as HTMLElement, path)
      },
      handleTabClick(el: HTMLElement, path: RouteLocationNormalized) {
        this.$router.push(path).then(() => {
          const scrollbar = unref((this.$refs.scrollbar as any).getWrapContainer())
          scrollbar.scrollTo({
            left: el.offsetLeft,
            behavior: 'smooth',
          })
        })
      },
      closeTab(fullPath: string) {
        this.removeTab(fullPath || '/')
      },
      isAffix(route: RouteRecordRaw) {
        return route.meta && route.meta.affix
      },
      onContextMenu(fullPath: string | undefined, e: MouseEvent) {
        const tempView = this.getVisitedRoutes.find((it) => it.fullPath === fullPath)
        if (!tempView) return
        const { clientX } = e
        const { x } = this.$el.getBoundingClientRect()
        e.preventDefault()
        this.selectRoute = tempView
        if (this.selectRoute) {
          this.showLeftMenu = this.isLeftLast(fullPath || '/')
          this.showRightMenu = this.isRightLast(fullPath || '/')
          const screenWidth = document.body.clientWidth
          this.contextMenuStyle.left = (clientX + 130 > screenWidth ? clientX - 130 - x - 15 : clientX - x + 15) + 'px'
          this.contextMenuStyle.top = '25px'
          this.showContextMenu = true
        }
      },
      removeTab(fullPath: string) {
        const findItemIndex = this.getVisitedRoutes.findIndex((it) => it.fullPath === fullPath)
        const findItem = this.getVisitedRoutes[findItemIndex]
        if (findItem) {
          this.removeVisitedRoute(findItem).then(() => {
            // 关闭当前
            if (this.currentTab === fullPath) {
              this.currentTab = this.getVisitedRoutes[findItemIndex - 1].fullPath
              // this.findLastRoutePath()
              this.$router.replace(this.currentTab)
            }
          })
        }
      },
      // context menu actions
      isLeftLast(tempRoute: string) {
        return this.getVisitedRoutes.findIndex((it) => it.fullPath === tempRoute) === 0
      },
      isRightLast(tempRoute: string) {
        return this.getVisitedRoutes.findIndex((it) => it.fullPath === tempRoute) === this.getVisitedRoutes.length - 1
      },
      onDropDownSelect(key: string) {
        switch (key) {
          case 'refresh':
            this.refreshRoute()
            break
          case 'close':
            this.closeAll()
            break
        }
      },
      refreshRoute() {
        if (this.refreshLoading) return
        this.refreshLoading = true
        setTimeout(() => {
          this.refreshLoading = false
        }, 2000)
        this.$router.replace({ path: '/redirect' + this.$route.path, query: this.$route.query })
      },
      closeLeft() {
        if (!this.selectRoute) return
        this.closeLeftVisitedView(this.selectRoute as RouteLocationNormalized).then(() => {
          if (this.$route.fullPath !== (this.selectRoute as RouteLocationNormalized).fullPath) {
            this.$router.push(this.findLastRoutePath())
          }
        })
      },
      closeRight() {
        if (!this.selectRoute) return
        this.closeRightVisitedView(this.selectRoute as RouteLocationNormalized).then(() => {
          if (this.$route.fullPath !== (this.selectRoute as RouteLocationNormalized).fullPath) {
            this.$router.push(this.findLastRoutePath())
          }
        })
      },
      closeAll() {
        this.closeAllVisitedView().then(() => {
          this.$router.push('/')
        })
      },
      // 关闭其他
      closeOther() {
        const currentPath = this.currentTab
        this.closeOtherVisitedView(currentPath)
      },
      closeMenu() {
        this.showContextMenu = false
      },
    },
  })
</script>

<style>
  .tab-bar__wrapper {
    display: flex;
  }
  .arco-dropdown-open .arco-icon-down {
    transform: rotate(180deg);
  }
</style>

<style lang="less" scoped>
  :deep {
    .arco-tabs-tab-active,
    .arco-tabs-tab-active:hover {
      color: #165dff;
    }
  }
  :deep(.arco-btn-outline) {
    border: 1px solid rgba(var(--primary-5), 0.7) !important;
    color: rgba(var(--primary-5), 0.7) !important;
    &:hover {
      border: 1px solid rgba(var(--primary-5), 1) !important;
      color: rgba(var(--primary-5), 1) !important;
    }
  }
  :deep(.arco-btn-disabled) {
    background-color: transparent !important;
    color: rgba(var(--primary-5), 0.7) !important;
  }
  :deep(.arco-btn-primary) {
    background-color: rgba(var(--primary-5), 0.8) !important;
    &:hover {
      background-color: rgba(var(--primary-5), 1) !important;
    }
  }

  // 覆盖tabs
  :deep(.arco-tabs-content) {
    display: none;
  }
  :deep(.arco-tabs-nav-type-card-gutter .arco-tabs-tab-active) {
    background: #fff;
  }
  :deep(.arco-tabs-nav::before) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab-list::before) {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    display: block;
    clear: both;
    height: 1px;
    background-color: var(--color-neutral-3);
    content: '';
  }
  :deep(.arco-tabs-nav-button-left) {
    margin-right: 8px;
    margin-left: 0;
  }
  :deep(.arco-tabs-nav-button-right) {
    margin-right: 10px;
    margin-left: 8px;
  }

  .vaw-tab-bar-container {
    position: relative;
    height: 52px;
    background: #f3f6f8;

    .vaw-tab-bar-body {
      height: 100%;
      display: flex;
      align-items: flex-end;
      white-space: nowrap;

      :deep(.arco-btn-size-small) {
        padding: 0 8px;
        height: 24px;
      }

      .arco-icon-hover {
        margin-right: 10px;
        margin-bottom: 10px;
        color: #1f2937;
        &.loadaing {
          color: #9ca3af;
        }
      }

      .close-opt {
        border-radius: @borderRadius @borderRadius 0 0;
        background: #fff;
        padding: 5px 8px;
        font-size: 14px;
        font-weight: 400;
        color: #1d2129;
        line-height: 22px;
        cursor: pointer;
      }

      .contex-menu-wrapper {
        position: absolute;
        width: 130px;
        z-index: 999;
        list-style: none;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
        background-color: #fff;
        padding-left: 0;
        & > li {
          width: 100%;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          padding: 5px 0;
          & button {
            width: 100%;
          }
        }
        & > li:hover {
          color: var(--primary-color);
        }
      }
      .humburger-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
      .tab-humburger-wrapper {
        margin-left: 40px;
        transition: margin-left @transitionTime;
      }
      .tab-no-humburger-wrapper {
        margin-left: 0;
        transition: margin-left @transitionTime;
      }

      .tab-item {
        cursor: pointer;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
        background: #f0f2f6;
        padding: 0 8px;
        height: 28px;
        margin-right: 2px;
        font-size: 14px;
        color: #767676;
        border-radius: 4px 4px 0 0;

        &.actived {
          background: #fff;
          color: #165dff;
          height: 32px;
        }
        .icon-item {
          display: inline-flex;
          width: 16px;
          height: 16px;
          max-width: 16px;
          max-height: 16px;
          margin-left: 5px;
          font-size: 12px;
          transform: scale(0.8);
          background-color: rgba(0, 0, 0, 0.12);
          border-radius: 50%;
          padding: 2px;
          transition: all 0.2s ease-in-out;
        }
      }
      .arrow-wrapper {
        font-size: 20px;
        color: #000;
      }
    }
  }
</style>
